package com.sagereal.wtc.factorymode.Activity;

import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.sagereal.wtc.factorymode.R;

import java.io.IOException;

public class MicActivity extends BaseActivity {
    private int mI = 0;
    private MediaRecorder mRecorder;
    private MediaPlayer mPlayer;
    private boolean mPermissionToRecordAccepted = false;
    private String[] mPermissions = {Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private Button mTestPass,mTestFail,mTestBtn;
    private TextView mTextView;
    private String mFileName;

    private boolean mHasRecording = false;
    private boolean mIsRecording = false;
    private boolean mIsPlaying = false;
    private long mRecordingStartTime;
    private static final long RECORDING_DURATION = 5000; // 5秒

    private Handler mHandler;
    private Runnable mRecordingRunnable;

    private BroadcastReceiver mScreenReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mic);
        setTitle(getString(R.string.title_mic_test));
        mFileName = getExternalFilesDir(null).getAbsolutePath() + "/recorded_audio.3gp";
        mTestPass = findViewById(R.id.test_pass);
        mTestFail = findViewById(R.id.test_fail);
        mTestBtn = findViewById(R.id.test_btn);
        mTextView = findViewById(R.id.notify_text);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED){
            showPermissionDialog();
        }
        mHandler = new Handler();
        initView();
        setupScreenReceiver();
    }



    private void initView() {
        mTestBtn.setOnClickListener(v -> {
            mTestBtn.setEnabled(false);
            mTestPass.setEnabled(false);
            startRecording();

            mRecordingRunnable = () -> {
                stopRecording();
                playRecording();
            };
            mHandler.postDelayed(mRecordingRunnable, RECORDING_DURATION);
        });

        mTestPass.setOnClickListener(v -> {
            if (mHasRecording) {
                Intent intent = new Intent(MicActivity.this, ItemTestActivity.class);
                intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1));
                intent.putExtra("status", "pass");
                intent.putExtra("check", getIntent().getStringExtra("check"));
                setResult(RESULT_OK, intent);
                finish();
            } else {
                mTestPass.setEnabled(false);
                Toast.makeText(this, R.string.mic_passbtn_notify, Toast.LENGTH_SHORT).show();
                new Thread(() -> {
                    try {
                        Thread.sleep(3000); // 等待Toast显示时间
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(() -> mTestPass.setEnabled(true));
                }).start();
            }
        });

        mTestFail.setOnClickListener(v -> {
            Intent intent = new Intent(MicActivity.this, ItemTestActivity.class);
            intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1));
            intent.putExtra("status", "fail");
            intent.putExtra("check", getIntent().getStringExtra("check"));
            setResult(RESULT_OK, intent);
            finish();
        });
    }

    /*提示权限需要申请*/
    private void showPermissionDialog() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.permission_ask)
                .setMessage(R.string.permission_content)
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })
                .setPositiveButton(getString(R.string.go_set), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                })
                .setCancelable(false)
                .show();
    }

    private void startRecording() {
        applySavedLanguage();
        mTextView.setText(R.string.recording);
        mTestBtn.setText(R.string.recording);

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mRecorder.start();
        mIsRecording = true;
        mRecordingStartTime = System.currentTimeMillis();
    }

    private void stopRecording() {
        applySavedLanguage();
        if (mRecorder != null) {
            try {
                mRecorder.stop();
            } catch (RuntimeException stopException) {
                stopException.printStackTrace();
            } finally {
                mRecorder.release();
                mRecorder = null;
                mIsRecording = false;
            }
        }
    }

    private void playRecording() {
        mPlayer = new MediaPlayer();
        try {
            mTextView.setText(R.string.recording_completion);
            mTestBtn.setText(R.string.testing);
            mPlayer.setDataSource(mFileName);
            mPlayer.prepare();
            mPlayer.start();
            mIsPlaying = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        mPlayer.setOnCompletionListener(mp -> {
            applySavedLanguage();
            mTextView.setText(R.string.mic_testing_completion);
            mTestBtn.setText(R.string.retest);
            mTestPass.setEnabled(true);
            mTestBtn.setEnabled(true);
            mHasRecording = true;
            mIsPlaying = false;
        });
    }

    private void setupScreenReceiver(){
        mScreenReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if(Intent.ACTION_SCREEN_OFF.equals(action)){
                    stopRecording();
                    stopPlaying();
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mScreenReceiver, filter);
    }

    private void stopPlaying(){
        if(mPlayer != null && mIsPlaying){
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
            mIsPlaying = false;
        }
    }

    protected void onDestroy(){
        super.onDestroy();
        unregisterReceiver(mScreenReceiver);
        stopRecording();
        stopPlaying();
    }

    protected void onResume(){
        super.onResume();
        mI++;
        if(mI > 1){
            Log.d("wentianci", "onResume: "+ mI);
            // 在 onResume 中再次检查相机权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                // 如果没有权限，则直接结束活动
                finish();
            }
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (!hasFocus) {
            onPause();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 取消延迟的停止录音和播放任务
        if (mHandler != null && mRecordingRunnable != null) {
            mHandler.removeCallbacks(mRecordingRunnable);
            mTestBtn.setText(R.string.retest);
        }
        // 停止正在进行的录音和播放
        stopRecording();
        stopPlaying();
        mTextView.setText(null);
        mTestPass.setEnabled(true);
        mTestBtn.setEnabled(true);
    }
}

